import puppeteer from 'puppeteer';
import axios from 'axios';
import xlsx from 'node-xlsx';
import fs from 'fs';
import setPageContent from 'puppeteer-core';
import GoLogin from '../../src/gologin.js';
import connect from 'puppeteer';
import readline from 'readline';
import { authenticator } from 'otplib';

let isRandomMove = true;
let path = 'c://fuel/fuel_address.xlsx';
let b = false;

async function step3(browser) {
  let page = await browser.newPage();
  page.setDefaultNavigationTimeout(90000);
  await page.goto('https://miles.plumenetwork.xyz/daily-checkin');

  await sleep(5000);
  const elementHandle2 = await page.$(
    '.css-1nmn613',
  );
  await elementHandle2.click();
  await sleep(5000);

  const a = await page.$(
    '.css-ymeid2',
  );
  await a.click();
}

(async () => {
  let id = process.argv[4];
  const option = process.argv[2].toUpperCase();
  getWsUrlById(id, async function (wsurl) {
    const browser = await puppeteer.connect({
      browserWSEndpoint: wsurl,
      ignoreHTTPSErrors: true,
      headless: false,
      defaultViewport: { width: 0, height: 0 },
      // extra_params: ['--start-maximized'],
    });
    switch (option) {
      case 'LOGIN':
        await step1(browser);
        return;
      case 'GET':
        await step2(browser);
        return;
      case 'SIGN':
        await step3(browser);
        return;
    }

  });
})();

async function step1(browser) {
  clickConfirm(browser);

  // newGL(profileId).uploadProfileCookiesToServer();
  const pages = await browser.pages();

  let page = await browser.newPage();
  for (let i = 0; i < pages.length; i++) {
    let pagez = pages[i];
    await pagez.close();
  }

  page.setDefaultNavigationTimeout(90000);
  await page.goto('https://miles.plumenetwork.xyz/');
  await sleep(3000);
  // await page.goto('https://miles.plumenetwork.xyz/');
  // await sleep(1000);
  const elementHandle = await page.$(
    'button[type="button"]',
  );

  try {
    await elementHandle.click();
    await sleep(800);
    const elementHandle2 = await page.$(
      '.css-1l113vs',
    );
    await elementHandle2.click();
    await sleep(800);

    const button = await (await page.evaluateHandle('document.querySelector("body > w3m-modal").shadowRoot.querySelector("wui-flex > wui-card > w3m-router").shadowRoot.querySelector("div > w3m-connect-view").shadowRoot.querySelector("wui-flex > w3m-wallet-login-list").shadowRoot.querySelector("wui-flex > w3m-connect-injected-widget").shadowRoot.querySelector("wui-flex > wui-list-wallet").shadowRoot.querySelector("button")')).asElement();
    await button.click();
    await sleep(5000);
    let length = (await browser.pages()).length;

    let page2 = (await browser.pages())[length - 1];
    let stringPromise = await page2.title();
    console.log(stringPromise);
    await sleep(5000);

    const psw = await page2.$(
      '#password',
    );
    await psw.type('383157zhangHAO', { delay: 60 });
    const btn = await page2.$(
      'button',
    );
    await btn.click();

    await sleep(8000);
    const btn4 = await page.$(
      'button[data-testid="sign-message-button"]',
    );
    await btn4.click();

    await sleep(3000);
  } catch (e) {
    console.log(e);
    // await step1(browser);
  }

  // const btn6 = await page.$(
  //   '.css-1nhw4tw',
  // );
  // await btn6.click();
  // await sleep(3000);

}

async function step2(browser) {
  try {
    const pages = await browser.pages();
    let page = await browser.newPage();
    for (let i = 0; i < pages.length; i++) {
      let pagez = pages[i];
      await pagez.close();
    }
    await page.setUserAgent('Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0')

    page.setDefaultNavigationTimeout(90000);
    // await page.goto('https://miles.plumenetwork.xyz/earn-miles');
    await page.goto('https://miles.plumenetwork.xyz/faucet');
    await sleep(5000);
    // await page.goto('https://miles.plumenetwork.xyz/faucet');
    // const cs = await page.$(
    //   'img[alt="Drip from Faucet"]',
    // );
    // await cs.click();
    //
    // await sleep(12000);
    // const lengt = (await browser.pages()).length;
    // let page1 = (await browser.pages())[lengt - 1];

    for (let i = 0; i < 5; i++) {
      try {
        await sleep(5000);
        // const lengt = (await browser.pages()).length;
        // let page2 = (await browser.pages())[lengt - 1];

        const elementHandle = await page.$('#cf-turnstile');
        const boundingBox = await elementHandle.boundingBox();

        // 如果元素存在，模拟点击坐标
        if (boundingBox) {
          const xWithinElement = boundingBox.x + 30.00;
          const yWithinElement = boundingBox.y + 30.00;
          await page.mouse.click(xWithinElement, yWithinElement);
        }

      } catch (e) {
        console.log(e);
      }

    }
    for (let i = 0; i < 5; i++) {
      try {
        await sleep(10000);
        const getToken = await page.$(
          '.css-1nhw4tw',
        );
        await getToken.click();
      } catch (e) {
        console.log(e);
      }
    }

  } catch (e) {
    console.log(e);
  }
}

async function clickConfirm(browser) {
  for (let i = 0; i < 100 || b; i++) {
    // Switch Network
    try {
      let page1 = (await browser.pages())[0];
      const button = await (await page1.evaluateHandle('document.querySelector("body > w3m-modal").shadowRoot.querySelector("wui-flex > wui-card > w3m-router").shadowRoot.querySelector("div > w3m-unsupported-chain-view").shadowRoot.querySelector("wui-flex > wui-flex:nth-child(2) > wui-list-network").shadowRoot.querySelector("button")')).asElement();
      await button.click();
      await sleep(3000);
    } catch (e) {
      console.log('');
    }

    try {
      const length = (await browser.pages()).length;
      let page4 = (await browser.pages())[length - 1];
      const btn4 = await page4.$(
        '.btn-primary',
      );
      await btn4.click();
    } catch (e) {
      let a;
    }
    await sleep(3000);
  }

}

// async function exportAddresses(psw) {
//
//   fs.mkdir('c://fuel', { recursive: true }, (err) => {
//     if (err) {
//       console.error(err);
//       return;
//     }
//     console.log('文件夹创建成功');
//   });
//
//   let browser = await getBrowser();
//   let newPage = await browser.newPage();
//   await gotoAddresses(newPage, psw);
//   //选地址
//   const items = await newPage.$$(
//     '.fuel_CardList>article>.fuel_Box-flex>.fuel_Box-flex',
//   );
//   const data = new Array();
//   for (const item of items) {
//     const name = await item.$(
//       'h6',
//     );
//     const address = await item.$(
//       'p',
//     );
//
//     const nameText = await newPage.evaluate(a => a.innerText, name);
//     const addresstext = await newPage.evaluate(a => a.innerText, address);
//     if (addresstext.startsWith('0x')) {
//       data.push([nameText, addresstext]);
//     }
//   }
//   console.log(data.toString());
//
//   const list = [
//     {
//       name: '地址', // 工作薄的名称
//       data: data,
//     },
//   ];
//
//   const buffer = xlsx.build(list);
//   let result = false;
//   await fs.writeFile(path, buffer, function (err) {
//     if (err) {
//       console.log(err, '导出excel失败');
//     } else {
//       console.log('导出excel成功!');
//       result = true;
//     }
//
//   });
//   await sleep(3000);
//   newPage.close();
//   return result;
// }

function sleep(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
}

function getWsUrlById(id, callback) {
  const fRead = fs.createReadStream('file.txt');
  const rl = readline.createInterface({
    input: fRead,
    terminal: false,
  });
  console.log(id);

  rl.on('line', function (line) {
    let strings = line.split('|');

    if (strings[0] === id) {
      console.log(strings[1]);
      rl.on('close', function () {
      });
      callback(strings[1]);
    }
  });
}

// module.exports.exportAddresses = exportAddresses;
// module.exports.refreshAccount = refreshAccount;
// module.exports.startGame = startGame;
